/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { Decorator, PropertyAssignment, SourceFile, SyntaxKind } from 'ts-morph';
import { IConstantResolver } from '../interface/IConstantResolver';
import { BaseAnalyzeResult } from '../../../framework';

/**
 * Decorator Parser Utility
 *
 * This utility class provides static methods for parsing TypeScript decorators,
 * extracting their arguments and resolving references to constants.
 * It's used
 * by annotation analyzers to extract metadata from HMRouter-related decorators.
 */
export class DecoratorParser {
  /**
   * Parse a decorator and create an analysis result
   *
   * This method extracts metadata from a decorator, including its name
   * and configuration options.
   * It resolves any constant references in
   * the decorator arguments.
   *
   * @param {Decorator} decorator - The decorator to parse
   * @param {IConstantResolver} constantResolver - Resolver for constant references
   * @param {SourceFile} sourceFile - The source file containing the decorator
   * @param {string} filePath - Path to the source file
   * @returns {BaseAnalyzeResult} Object containing the extracted decorator metadata
   */
  static parseDecorator(
    decorator: Decorator,
    constantResolver: IConstantResolver,
    sourceFile: SourceFile,
    filePath: string
  ): BaseAnalyzeResult {
    // Initialize with basic decorator information
    const decoratorResult: BaseAnalyzeResult = {
      annotation: decorator.getName(),
      name: '',
      sourceFilePath: ''
    };

    // Parse and merge the arguments
    const args = this.parseDecoratorArguments(decorator, constantResolver, sourceFile, filePath);
    Object.assign(decoratorResult, args);

    return decoratorResult;
  }

  /**
   * Parse the arguments of a decorator
   *
   * This method extracts the configuration options from a decorator's argument list.
   * It supports object literal expressions and resolves constant references in
   * property values.
   *
   * @param {Decorator} decorator - The decorator to parse arguments from
   * @param {IConstantResolver} constantResolver - Resolver for constant references
   * @param {SourceFile} sourceFile - The source file containing the decorator
   * @param {string} filePath - Path to the source file
   * @returns {BaseAnalyzeResult} Object containing the parsed arguments
   */
  static parseDecoratorArguments(
    decorator: Decorator,
    constantResolver: IConstantResolver,
    sourceFile: SourceFile,
    filePath: string
  ): BaseAnalyzeResult {
    const argResult: BaseAnalyzeResult = {
      annotation: decorator.getName(),
      name: '',
      sourceFilePath: '',
    };

    decorator.getArguments().forEach((arg) => {
      // Process object literal arguments like @HMRouter({key: value})
      const objLiteral = arg.asKind(SyntaxKind.ObjectLiteralExpression);

      if (objLiteral) {
        objLiteral.getProperties().forEach((prop) => {
          this.hondleObjLiteral(prop, constantResolver, sourceFile, filePath, argResult);
        });
      }
    });

    return argResult;
  }

  static hondleObjLiteral(
    prop: any,
    constantResolver: IConstantResolver,
    sourceFile: SourceFile,
    filePath: string,
    argResult: BaseAnalyzeResult
  ): void {
    if (prop.getKind() === SyntaxKind.PropertyAssignment) {
      const propertyAssignment = prop as PropertyAssignment;
      const propertyName = propertyAssignment.getName();
      const initializer = propertyAssignment.getInitializer();

      if (initializer) {
        // Use constant resolver to handle references to string constants
        const propertyValue = constantResolver.resolvePropertyValue(initializer, sourceFile, filePath);
        Reflect.set(argResult, propertyName, propertyValue);
      }
    }
  }
}
